package com.tollge.business.core;

import lombok.extern.log4j.Log4j2;

import javax.ws.rs.container.ContainerRequestContext;
import javax.ws.rs.container.ContainerRequestFilter;
import javax.ws.rs.container.ContainerResponseContext;
import javax.ws.rs.container.ContainerResponseFilter;
import javax.ws.rs.ext.Provider;

@Provider
@Log4j2
public class RequestLogFilter implements ContainerRequestFilter, ContainerResponseFilter {

    /**
     * 超过x毫秒, 则打日志
     */
    public static final long UN_HEALTH_TIME = 50L;

    @Override
    public void filter(ContainerRequestContext requestContext) {
        long requestStartTime = System.currentTimeMillis();
        requestContext.setProperty("requestStartTime", requestStartTime);
    }

    @Override
    public void filter(ContainerRequestContext requestContext, ContainerResponseContext responseContext) {
        Object requestStartTimeObj = requestContext.getProperty("requestStartTime");
        if(requestStartTimeObj != null) {
            long requestStartTime = (long) requestStartTimeObj;
            long requestFinishTime = System.currentTimeMillis();
            long duration = requestFinishTime - requestStartTime;
            if (duration > UN_HEALTH_TIME) {
                log.warn("request " + requestContext.getUriInfo().getPath() + " take " + duration + "ms");
            }
        }
    }
}
